<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :align-center="true" width="50%" :title="`位置信息`">
    <el-form
      ref="jobTagsFormRef"
      :rules="rules"
      :disabled="dialogData.isView"
      :model="dialogData.itemInfo"
      label-width="2em"
      label-suffix=" :"
      :hide-required-asterisk="dialogData.isView"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <section class="form-s2" style="align-items: flex-start">
            <h3 style="margin: 0 2rem">地址信息</h3>
            <div class="jobaddress-marker-tip">
              <div class="addr-tag-content">
                <el-icon style="margin-right: 0.25rem" size="24">
                  <Place />
                </el-icon>
                <!-- 面试地址-{{ jobAddressStr }} -->
                <el-input v-model="dialogData.itemInfo.address" placeholder="地址信息" />
                <el-icon class="addr-close" @click="handleRemoveMarkJobAddress">
                  <CircleClose />
                </el-icon>
              </div>
            </div>
            <div class="container">
              <div class="map-search-box">
                <el-input
                  v-model="mapAddressQuery"
                  placeholder="请输入地址查询"
                  :prefix-icon="Search"
                  @keyup.enter="queryCoord"
                />
                <el-button @click="queryCoord" type="primary" :icon="Search">查找</el-button>
                <el-button @click="handleMarkJobAddress" type="primary" :icon="Check">标记发送地址</el-button>
              </div>
              <div id="mcontainer" class="map-box"></div>
            </div>
          </section>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="btnLoading" :icon="Link"> 发送位置 </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, shallowRef, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { getOptTitle, OptEnum } from "@/biz/eenum/appEnum";
import { DialogParam } from "@/biz/interface/DialogType";
import { Link, Search, Check } from "@element-plus/icons-vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { getCoordFromAddress, getAddressFromCoord } from "@/api/modules/common/map";
import saveMsg from "@/views/im/utils/saveMsg.js";
import { MESSAGE_TYPE } from "@/IM/constant";
//页面的数据
interface AddressDialogOption extends DialogParam {
  //弹出表单的标题
  title: string;
  //是否是查看状态，查看状态是不可以提交数据
  isView: boolean;
  //当前的数据对象
  itemInfo: {
    // 位置信息
    address: string;
    posX?: number;
    posY?: number;
  };
  //其它的数据都继续在这里加
  addressLocation: string;
}
//提交按钮，避免多次提交
const btnLoading = ref(false);
//弹出框的参数
const dialogVisible = ref(false);
//当前表单数据在这里初始化
const dialogData = reactive<AddressDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  isView: false,
  itemInfo: {
    address: ""
  },
  //查找的地址坐标
  addressLocation: ""
});
const chooseAddress = () => {
  dialogVisible.value = true;
};
const map = shallowRef(null);
const amap = shallowRef(null);
const mapConfig = {
  key: "ffdc25d48476be43db69ee51b49b80e9",
  version: "2.0",
  plugins: ["AMap.DistrictSearch"]
};
const mapInitInfo = {
  viewMode: "2D",
  zoom: 12,
  center: [105.602725, 37.076636]
};

const initMap = () => {
  AMapLoader.load(mapConfig)
    .then(AMap => {
      map.value = new AMap.Map("mcontainer", mapInitInfo);
      amap.value = AMap;
      // map.value.add(new AMap.Marker({
      //   position: new AMap.LngLat(121.550357,29.874556)
      // }))
    })
    .catch(e => console.log(e));
};

// 接收父组件传过来的参数
const acceptParams = (params: DialogParam): void => {
  // console.log("接收到的参数 :", params);
  dialogData.optType = params.optType;
  dialogData.rowData = params.rowData;
  dialogData.isView = dialogData.optType === OptEnum.VIEW;
  dialogData.title = getOptTitle(dialogData.optType);
  initItemInfo();
  dialogVisible.value = true;
};

//初始化页面的数据
const initItemInfo = (): void => {
  dialogData.itemInfo = {
    address: ""
  };
  dialogData.addressLocation = "";
};

//数据较验
const rules = reactive({
  address: [{ required: true, message: "请填写详细地址", trigger: "blur" }]
});

// 提交数据
const jobTagsFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  jobTagsFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      if (dialogData.addressLocation) {
        sendPositionMessage(dialogData.itemInfo);
      }
    } catch (error) {
    } finally {
      btnLoading.value = false;
    }
  });
};
const sendPositionMessage = async data => {
  let customEvent = "customEvent";
  let customExts = data;
  let options = {
    customEvent,
    customExts
  };
  saveMsg(options, MESSAGE_TYPE.LOCATION);
  dialogVisible.value = false;
};

const jobAddressStr = ref("");
const jobAddressObject = ref({} as any);
const mapAddressQuery = ref("");
const handleMarkJobAddress = () => {
  if (Object.keys(jobAddressObject.value).length > 0) {
    jobAddressStr.value =
      jobAddressObject.value.addressComponent.province +
      jobAddressObject.value.addressComponent.city +
      jobAddressObject.value.addressComponent.district +
      mapAddressQuery.value;
    //格式化需要的数据

    // console.log("选择的地址：", dialogData.addressLocation);
    dialogData.itemInfo.address = jobAddressStr.value;
    if (dialogData.addressLocation) {
      let coord = dialogData.addressLocation.split(",").map((e: string) => parseFloat(e));
      if (coord) {
        dialogData.itemInfo.posY = coord[0];
        dialogData.itemInfo.posX = coord[1];
      }
    } else {
      ElMessage.error("选择的位置需要精确到区域.");
    }
  } else {
    ElMessage.error("请先进行地址查询！");
  }
};

const handleRemoveMarkJobAddress = () => {
  initItemInfo();
  jobAddressStr.value = "";
};

const queryCoord = () => {
  if (!mapAddressQuery.value) return;
  getCoordFromAddress(mapAddressQuery.value)
    .then(res => res.json())
    .then((res: any) => {
      // const markerClick = (e:any) => {
      //   console.log(e)
      // }
      // jobAddressObject.value = res.geocodes[0];
      dialogData.addressLocation = res.geocodes[0].location;
      getAddressFromCoord(res.geocodes[0].location)
        .then(address => address.json())
        .then((ares: any) => {
          jobAddressObject.value = ares.regeocode;
          // console.log(jobAddressObject.value)
        });
      res.geocodes.forEach((geo: any, idx: number) => {
        let coord = geo.location.split(",").map((e: string) => parseFloat(e));
        if (idx == 0) {
          map.value!.setCenter(coord);
        }
        let marker = new amap.value!.Marker({
          position: new amap.value!.LngLat(coord[0], coord[1]),
          title: geo.formatted_address,
          draggable: true,
          cursor: "move"
        });
        // marker.on('click', markerClick)
        map.value!.add(marker);
      });
    });
};
//页面事件
const emits = defineEmits(["refresh-data"]);

//页面参数
defineExpose({
  acceptParams,
  chooseAddress
});

watch(dialogVisible, n => {
  if (n) {
    initMap();
  }
});
</script>

<style scoped lang="scss">
.exit-interview-box {
  display: flex;
  align-items: center;
  justify-content: space-around;
  height: 40px;
  line-height: 40px;
  font-size: 1.1rem;
  font-weight: 600;
  border: 1px solid var(--el-color-primary-light-5);
  margin: 5px;
  border-radius: 5px;

  span {
    margin: 0 10px;
    // border: 1px solid red;
    flex: 1;
  }

  .el-button {
    // border: 1px solid red;
    width: 80px;
  }
}

#mcontainer {
  width: 95%;
  height: 26rem;
  margin-left: 2rem;
  border-radius: 4px;
  margin-bottom: 10px;
}

.jobaddress-marker-tip {
  width: 95%;
  margin-left: 2rem;
  margin-bottom: 0.5rem;
}
.addr-tag-content {
  display: flex;
  align-items: center;
  color: rgb(117, 117, 117);
  font-size: 1.125rem;
  font-weight: bold;
  padding: 0.45rem;
  border: 1px solid white;
  border-radius: 4px;
  & .el-icon {
    font-size: 1.4rem;
    color: red;
  }
  cursor: default;
  & .addr-close {
    visibility: hidden;
    color: rgb(161, 161, 161);
    margin-left: 0.25rem;
    font-size: 1.125rem;
    cursor: pointer;
    &:hover {
      color: rgb(114, 114, 114);
    }
  }
  &:hover .addr-close {
    visibility: visible;
  }
  &:hover {
    border: 1px solid rgb(221, 221, 221);
    border-radius: 4px;
  }
}

.form-s1 {
  // border: 1px solid green;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: left;
  border-radius: 0.25rem;
}
.form-s2 {
  @extend .form-s1;
}
.container{
  width: 100%;
  position: relative;
}

.map-search-box {
  position: absolute;
  z-index: 100;
  width: 60%;
  display: flex;
  margin-left: 2.5rem;
  top: 0.5rem;
}
</style>
